package migrator

import (
	"fmt"
	"strings"

	"github.com/xwb1989/sqlparser"
)

// ShardingDDLSQLs generate DDL sqls
// 生成的 SQL table name 会是 base_%04d
func ShardingDDLSQLs(sqlTemp string, mod int) ([]string, error) {
	if mod <= 1 {
		return []string{sqlTemp}, nil
	}

	// 只处理 DDL
	stmt, err := sqlparser.Parse(sqlTemp)
	if err != nil {
		return nil, err
	}
	ddl, ok := stmt.(*sqlparser.DDL)
	if !ok {
		return nil, fmt.Errorf("invalid DDL SQL: %s", sqlTemp)
	}

	// 重新生成
	baseName := ddl.NewName.Name.String()
	sqls := make([]string, 0)
	for i := 0; i < mod; i++ {
		tableName := shadingTableName(baseName, i)
		sqls = append(sqls, strings.Replace(sqlTemp, baseName, tableName, 1))
	}

	return sqls, nil
}

func shadingTableName(baseName string, i int) string {
	return fmt.Sprintf("%s_%04d", baseName, i)
}
